package com.hsmpay.qian4.service.ds.impl;

import com.hsmpay.common.pojo.user.User;
import com.hsmpay.common.util.NumberUtil;
import com.hsmpay.mobile.action.account.scanCodePay.MD5;
import com.hsmpay.mobile.action.account.scanCodePay.ScanCodePayParam;
import com.hsmpay.mobile.action.account.scanCodePay.SignUtils;
import com.hsmpay.mobile.pojo.other.Settings;
import com.hsmpay.mobile.service.other.SettingsService;
import com.hsmpay.qian4.pojo.PurchaseResult;
import com.hsmpay.qian4.service.ds.JQQRCodePayService;
import com.hsmpay.utils.DesUtil;
import com.hsmpay.utils.JSONUtil;
import com.hsmpay.utils.WriteFile;
import com.hsmpay.utils.system.ConConfig;
import javapns.org.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("ds_JQQRCodePayService")
public class JQQRCodePayServiceImpl implements JQQRCodePayService {

    private static WriteFile wf = new WriteFile("ds_JQQR");
    private static Logger log = LoggerFactory.getLogger(JQQRCodePayServiceImpl.class);
    private static final String version = "1.0.0";
    private static final String requestIp = "127.0.0.1";//请求方公网IP
    private static String urlStr = ConConfig.getAttribute("URL_OFFICIAL");
    private static final String HSM_CUSTOMER_NO = ConConfig.getAttribute("HSM_JQQR_CUSID");
    private static final String HSM_MD5KEY = ConConfig.getAttribute("HSM_JQQR_MD5KEY");
    @Resource(name = "settingsService")
    protected SettingsService<Settings, Long> settingsService;


    /**
     * 获取消费二维码
     * @return
     * @throws Exception
     */
    public PurchaseResult getQRCode(ScanCodePayParam scanCodePayParam, User user) throws Exception {

        String notifyUrl = "http://"+urlStr+"/proOneMobile/JQNotify.action";
        String reqUrl = "http://app.1spay.com/agent/transReq.action";

        String outTradeNo = scanCodePayParam.getOutTradeNo();
        double totalFee = Double.valueOf(scanCodePayParam.getTotalFee());

        log.info("【进钱二维码-收款 请求参数】outTradeNo: "+ outTradeNo);
        log.info("【进钱二维码 请求参数】totalFee: "+ totalFee);

        wf.log("【进钱二维码-收款 请求参数】outTradeNo: "+outTradeNo, "调试");
        wf.log("【进钱二维码-收款 请求参数】totalFee: "+totalFee, "调试");

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr = sdf.format(date);
        String reqDate = dateStr.substring(0,8);
        String reqTime = dateStr.substring(8);

        String customer_no = "";
        String MD5Key = "";
        String clearWay = settingsService.getMainValueByFk("WHETHER_CLEAR_BY_JQ");
        if(clearWay.equals("1") && StringUtils.isNotBlank(user.getJQCusId()) && StringUtils.isNotBlank(user.getJQMD5Key())){
            customer_no = user.getJQCusId();
            MD5Key = user.getJQMD5Key();
        }else {
            customer_no = HSM_CUSTOMER_NO;
            MD5Key = HSM_MD5KEY;
        }

        SortedMap<String,String> map = new TreeMap<>();
        map.put("version", version);
        map.put("service","0002");//进钱微信扫码支付
        map.put("reqDate", reqDate);
        map.put("transAmount", String.valueOf(NumberUtil.roundF2(totalFee*100).longValue()));//金额转为分
        map.put("bgReturnUrl", notifyUrl);
        map.put("customerNo", customer_no);
        map.put("externalId", outTradeNo);
        map.put("selfData", DesUtil.generate32Key());
        map.put("requestIp", requestIp);
        map.put("reqTime", reqTime);
        map.put("description", scanCodePayParam.getBody());

        Map<String,String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() +1) * 10);
        SignUtils.buildPayParams(buf,params,false);
        String preStr = buf.toString();
        String sign = MD5.sign(preStr, "&key=" + MD5Key, "utf-8");
        map.put("sign", sign);

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.putAll(map);

        JSONObject jsonObject = new JSONObject(paramMap);
        log.info("【进钱二维码-收款 请求参数】:" + jsonObject.toString());

        Map<String, String> resultMap = new HashMap<>();
        if(ConConfig.isFormal()){
            wf.log("【进钱二维码-收款】请求环境:生产环境", "调试");

            CloseableHttpResponse response = null;
            CloseableHttpClient client = null;
            try {
                HttpPost httpPost = new HttpPost(reqUrl);
                StringEntity entityParams = new StringEntity(jsonObject.toString(), "utf-8");
                httpPost.setEntity(entityParams);
                httpPost.setHeader("Content-Type", "text/xml;charset=ISO-8859-1");
                client = HttpClients.createDefault();
                response = client.execute(httpPost);
                if (response != null && response.getEntity() != null) {
                    JSONObject jsonObj = new JSONObject(EntityUtils.toString(response.getEntity()));
                    log.info("【进钱二维码-收款 响应参数】:" + jsonObj.toString());
                    Map<String, String> resultJsonMap = JSONUtil.parseToBean(jsonObj.toString());
                    String payInfoString = resultJsonMap.get("payInfo");
                    if(StringUtils.isNotBlank(payInfoString)){
                        JSONObject payInfo = new JSONObject(payInfoString);
                        Iterator<String> payInfoItr = payInfo.keys();
                        while (payInfoItr.hasNext()) {
                            String name = payInfoItr.next();
                            resultMap.put(name, payInfo.getString(name));
                        }
                        jsonObj.remove("payInfo");
                    }
                    Iterator<String> nameItr = jsonObj.keys();
                    while (nameItr.hasNext()) {
                        String name = nameItr.next();
                        resultMap.put(name, jsonObj.getString(name));
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                log.error("【进钱二维码-收款】 系统异常!");
            }
        }else {
            wf.log("【进钱二维码-收款】请求环境:测试环境", "调试");
            Map resultMap2 =  new HashMap<String, Object>();
            resultMap2.put("appId", "wx8632a91376b81e24");
            resultMap2.put("timeStamp", "1473130115327");
            resultMap2.put("status", "0");
            resultMap2.put("signType", "MD5");
            resultMap2.put("package", "prepay_id=wx20160906104835c93c892dc20513630129");
            resultMap2.put("callback_url", "");
            resultMap2.put("nonceStr", "1473130115327");
            resultMap2.put("paySign", "D5E9444409354CB0F8C90C6C866DDA4F");


            Map resultMap1 =  new HashMap<String, Object>();
            resultMap1.put("message", "成功");
            resultMap1.put("sign", "5AB79D21EA969ADED363ECEC705FDCA1");
            //  resultMap1.put("payInfo", resultMap2);
            resultMap1.put("customerNo", "8611116424");
            resultMap1.put("resultCode", "1625231433");
            resultMap1.put("payUrl", "https://pay.swiftpass.cn/pay/jspay?token_id=3f8a021cdf16590db471252a6e76c3e8&showwxtitle=1");
            resultMap1.put("code", "0");
            resultMap1.put("status", "0");
            resultMap1.put("appId", "wx8632a91376b81e24");
            resultMap1.put("timeStamp", "1473130115327");
            resultMap1.put("status", "0");
            resultMap1.put("signType", "MD5");
            resultMap1.put("package", "prepay_id=wx20160906104835c93c892dc20513630129");
            resultMap1.put("callback_url", "");
            resultMap1.put("nonceStr", "1473130115327");
            resultMap1.put("paySign", "D5E9444409354CB0F8C90C6C866DDA4F");

            // String info = "{\"message\":\"成功\",\"sign\":\"570F2211FF1C13BFECEE66A2D5220796\",\"payInfo\":\"{\"appId\":\"wx8632a91376b81e24\",\"timeStamp\":\"1473668719286\",\"status\":\"0\",\"signType\":\"MD5\",\"package\":\"prepay_id=wx20160912162519bc70ae17990352093168\",\"callback_url\":null,\"nonceStr\":\"1473668719286\",\"paySign\":\"C7366069E6BBC1CC790A635CB67A13AE\"}\",\"customerNo\":\"8611116424\",\"resultCode\":\"1625231433\",\"payUrl\":\"https://pay.swiftpass.cn/pay/jspay?token_id=3f8a021cdf16590db471252a6e76c3e8&showwxtitle=1\",\"code\":\"0\"}";
            //Map<String, String> resultDebugMap = JSONUtil.parseToBean(info);
            resultMap = resultMap1;
        }

        PurchaseResult pr = new PurchaseResult();
        pr.setReqMsg("获取交易订单失败,请稍后再试!");
        pr.setStatus(0);
        pr.setReqCode("0001");

        if(resultMap.isEmpty()){
            pr.setReqMsg("获取交易订单失败,请稍后再试!");
            return pr;
        }

        String code = resultMap.get("code");

        if(code.equals("0")){//通讯成功
            if((resultMap.containsKey("payUrl") && StringUtils.isNotBlank(resultMap.get("payUrl"))) || (resultMap.containsKey("payImg") && StringUtils.isNotBlank(resultMap.get("payImg")))){
                pr.setPayUrl(resultMap.get("payUrl"));//返回的扫码支付地址
                pr.setAppId(resultMap.get("appId"));
                pr.setTimestamp(resultMap.get("timeStamp"));
                pr.setNonceStr(resultMap.get("nonceStr"));
                pr.setPrepayId(resultMap.get("package"));
                pr.setPaySign(resultMap.get("paySign"));
                pr.setPayImg(resultMap.get("payImg"));
                pr.setCustomerNo(customer_no);
                pr.setReqMsg("获取交易订单成功!");
                pr.setReqCode("0000");
            }else {
                pr.setReqMsg("获取交易订单失败,请稍后再试!");
            }
        }else {
            String message = resultMap.get("message");
            pr.setReqMsg(message);
        }
        return pr;
    }
}
